package aop.xyz.myapp.dao.account;

import java.util.ArrayList;
import java.util.List;

import aop.xyz.myapp.PessimisticLockingFailureException;
import aop.xyz.myapp.dao.GeneralDAO;
import aop.xyz.myapp.domain.IEntity;
import aop.xyz.myapp.domain.account.User;

public class UserDAO extends GeneralDAO<User, Long>{
	private int shouldRetries = 2;
	private int numRetries = 0;

	public User get(Long id) {
		User user = new User();
		user.setId(id);
		user.setStatus(IEntity.STATUS_PERSISTED);
		return user;
	}

	public User del(Long id) {
		User user = new User();
		user.setId(id);
		user.setStatus(IEntity.STATUS_DELETED);
		return user;
	}

	public void del(User user) {
		user.setStatus(IEntity.STATUS_DELETED);
	}

	public List<User> del(List<Long> ids) {
		List<User> deletedUsers = new ArrayList<User>();
		for (Long id : ids) {
			User user = new User();
			user.setId(id);
			user.setStatus(IEntity.STATUS_DELETED);
			deletedUsers.add(user);
		}
		return deletedUsers;
	}

	public List<User> getAll() {
		return null;
	}

	public void saveOrUpdate(User user)
			throws PessimisticLockingFailureException {
		// here we do a hack, only after twice trial the user could be saved.
		if (numRetries < shouldRetries) {
			numRetries++;
			throw new PessimisticLockingFailureException(
					"DB locked by another operation");
		}

		user.setStatus(IEntity.STATUS_PERSISTED);
	}

	public void setShouldRetries(int shouldRetries) {
		this.shouldRetries = shouldRetries;
	}

	public int getShouldRetries() {
		return shouldRetries;
	}
}
